<template>
    <div class="page-100 repair-fault-des-layout">
        <!--@focus="textAreaFoculHandler"-->
        <!--@blur="textAreaBlurHandler"-->
        <textarea id="textfocus"
                  @click="clickTextHandle"
                  v-on:focus="focusIpt"
                  v-on:blur="blurIpt"
                  v-model="desfault"
                  class="weui-textarea fault-des-content-part"
                  placeholder="请描述故障"
                  rows="5"
                  maxlength="200"></textarea>
        <!--图片显示组件-->
        <ImageShowComponent
                class="fault-des-img-part"
                :imageObjList="images"
                :isShowDelLogo="true"
                :qiNiuUrl="qn_domain"
                v-on:imageDeleteEvent="deleteImgHandler"/>
        <!--底部导航栏操作组件-->
        <MultimediaComponent
                style="padding-top: 1rem"
                :isMultimediaFocus="isMultimediaFocus"
                v-on:clickVoicePanel="clickVoicePanel"
                v-on:clickPicture="clickPicture"
                v-on:clickPhoto="clickPhoto"
                v-on:touchStartAudio="touchStartAudio"
                v-on:touchEndAudio="touchEndAudio"
                v-on:clickKeyboard="clickKeyboard"/>
        <!--确定按钮-->
        <!--<a href="javascript:;" @click="handleClick" class="weui-btn weui-btn_primary button-margin-part">确定</a>-->
        <div style="padding-left: 0.4rem;padding-right: 0.4rem">
            <yd-button size="large" type="primary" @click.native="handleClick" style="background-color:#3cc8a8;color:white;height: 40px;">确定</yd-button>
        </div>
    </div>
</template>

<script>
    import MultimediaComponent from "@/components/MultimediaComponent.vue";
    import ImageShowComponent from "@/components/ImageShowComponent.vue";
    import {repairOrderSavedInstance,qn_domain} from '../../globalVariables';
    export default {
        name: "repairFaultDescription",
        data() {
            return {
                desfault: '',
                // images: [
                //     'http://static.ydcss.com/uploads/ydui/1.jpg',
                //     'http://static.ydcss.com/uploads/ydui/2.jpg',
                //     'http://static.ydcss.com/uploads/ydui/3.jpg'
                // ],
                // images: [
                //     "wxLocalResource://imageid123456789987654321", "wxLocalResource://imageid987654321123456789"
                // ]
                images: [],
                repairData: [],
                isFocus: false,
                isMultimediaFocus: false,
                qn_domain: '',
                isSendRepairState: false,
                startTx: 0,
                startTy: 0,
            }
        },
        components: {
            MultimediaComponent,
            ImageShowComponent,
        },
        directives: {
            focus: {
                inserted(element, binding) {
                    if (binding.value) {
                        element.focus()
                    } else {
                        element.blur()
                    }
                },
                componentUpdated(element, binding) {
                    if (binding.value) {
                        element.focus()
                    } else {
                        element.blur()
                    }
                },
            },
        },
        created() {
            this.qn_domain = localStorage.getItem(qn_domain);
            this.repairData = JSON.parse(localStorage.getItem(repairOrderSavedInstance));
            if (this.repairData[7].images === null || this.repairData[7].images === '') {

            } else {
                if (this.repairData[7].images.length > 0) {
                    this.images = this.repairData[7].images;
                }
            }
            this.desfault = this.repairData[7].content;
        },
        beforeRouteLeave(to,from,next) {
            document.activeElement.blur();
            if (this.isSendRepairState === true) {
                next();
            } else {
                // const answer = window.confirm('离开后已填写的故障描述内容将会丢失');
                // if (answer) {
                //     next()
                // } else {
                //     next(false)
                // }
                weui.confirm('离开后已填写的故障描述内容将会丢失', {
                    title: '',
                    buttons: [{
                        label: '离开',
                        type: 'primary',
                        onClick: function () {
                            console.log('no');
                            next();
                        }
                    }, {
                        label: '取消',
                        type: 'default',
                        onClick: function () {
                            console.log('yes');

                            next(false);
                        }
                    }]
                });
            }
        },
        methods: {
            clickVoicePanel() {
                if (localStorage.getItem(rainAllowRecord) === '' || localStorage.getItem(rainAllowRecord) === null
                    || localStorage.getItem(rainAllowRecord) === undefined || localStorage.getItem(rainAllowRecord) === '0') {
                    //没有授权过
                    wx.startRecord({
                        success: function () {
                            localStorage.setItem(rainAllowRecord,'1');
                            wx.stopRecord();
                        } ,
                        cancel: function () {
                            localStorage.setItem(rainAllowRecord,'0');
                        }
                    });
                }
            },
            //确定按钮
            handleClick() {
                this.isSendRepairState = true;
                this.repairData[7].images = [];
                this.repairData[7].content = this.desfault;
                this.repairData[7].images = this.images;
                localStorage.setItem(repairOrderSavedInstance,JSON.stringify(this.repairData));
                this.$router.back();
            },
            deleteImgHandler(payload) {
                var index = payload.index;
                this.$dialog.confirm({
                    title: '',
                    mes: '是否要删除该图片？',
                    opts: () => {
                        this.images.splice(index,1);
                    }
                });
            },
            /** 开始录音事件 */
            touchStartAudio(payload) {
                let that = this;
                var localId = '';

                var touches = payload.event.touches[0];
                this.startTx = touches.clientX;
                this.startTy = touches.clientY;

                this.$dialog.loading.open('语音录制中...');

                wx.ready(function () {
                    wx.startRecord({
                        success: function () {
                            wx.onVoiceRecordEnd({
                                // 录音时间超过一分钟没有停止的时候会执行 complete 回调
                                complete: function (res) {
                                    that.$dialog.loading.close();
                                    localId = res.localId;
                                    // that.device = res.localId;
                                    // that.$dialog.confirm({
                                    //     title: '一分钟语音测试',
                                    //     mes: localId,
                                    //     opts: () => {
                                    //         that.$dialog.toast({mes: '你点了确定', timeout: 1000});
                                    //     }
                                    // });
                                    if (localId == '') {
                                        console.log('localId is "" ')
                                    } else {
                                        wx.ready(function () {
                                            wx.translateVoice({
                                                localId: localId, // 需要识别的音频的本地Id，由录音相关接口获得
                                                isShowProgressTips: 1, // 默认为1，显示进度提示
                                                success: function (res) {
                                                    // 语音识别的结果
                                                    that.desfault = res.translateResult;
                                                }
                                            });
                                        });
                                    }
                                }
                            });
                        }
                    });
                });
            },
            /** 停止录音事件 */
            touchEndAudio(payload) {
                let that = this;
                var localId = '';

                var touches = payload.event.changedTouches[0];
                var distanceY = this.startTy - touches.clientY;

                this.$dialog.loading.close();

                if (distanceY > 50) {
                    console.log("取消发送信息");
                    wx.stopRecord({
                        success: function (res) {
                            localId = res.localId;
                        }
                    })
                }else {
                    console.log("发送信息");

                    //停止录音接口
                    wx.ready(function () {
                        wx.stopRecord({
                            success: function (res) {
                                localId = res.localId;
                                // that.device = res.localId;
                                // that.$dialog.confirm({
                                //     title: '语音测试',
                                //     mes: localId,
                                //     opts: () => {
                                //         that.$dialog.toast({mes: '你点了确定', timeout: 1000});
                                //     }
                                // });
                                if (localId == '') {
                                    console.log('localId is "" ')
                                } else {
                                    wx.ready(function () {
                                        wx.translateVoice({
                                            localId: localId, // 需要识别的音频的本地Id，由录音相关接口获得
                                            isShowProgressTips: 1, // 默认为1，显示进度提示
                                            success: function (res) {
                                                // 语音识别的结果
                                                that.desfault = res.translateResult;
                                            }
                                        });
                                    });
                                }
                            }
                        });
                    });

                }
            },
            clickPicture() {
                console.log('clickPicture');
                let that = this;
                if (this.images.length < 3) {
                    wx.chooseImage({
                        count: 3-this.images.length, // 默认9
                        sizeType:['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['album'], //'album', 'camera' 可以指定来源是相册还是相机，默认二者都有
                        success: function (res) {
                            console.log('chooseImage success');
                            console.log(res);
                            console.log(res.localIds);
                            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                            // that.images = localIds;
                            for (var i = 0;i<localIds.length;i++) {
                                var imageObj = new Object();
                                imageObj.imageType = 'WeiXin';
                                imageObj.imageUrl = localIds[i];
                                that.images.push(imageObj);
                            }
                        }
                    });
                } else {
                    this.$dialog.toast({
                        mes: "已经达到最高选择数量",
                        timeout: 1500
                    });
                }
            },
            clickPhoto() {
                console.log('clickPhoto');
                let that = this;
                if (this.images.length < 3) {
                    wx.chooseImage({
                        count: 3-this.images.length, // 默认9
                        sizeType:['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                        success: function (res) {
                            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                            // that.images = localIds;
                            for (var i = 0;i<localIds.length;i++) {
                                var imageObj = new Object();
                                imageObj.imageType = 'WeiXin';
                                imageObj.imageUrl = localIds[i];
                                that.images.push(imageObj);
                            }
                        }
                    });
                } else {
                    this.$dialog.toast({
                        mes: "已经达到最高选择数量",
                        timeout: 1500
                    });
                }
            },
            scanHandleClick() {
                let that = this;
                wx.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode"], // "qrCode","barCode"可以指定扫二维码还是一维码，默认二者都有
                    success: function (res) {
                        var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                        var obj = JSON.parse(result);
                        that.device = obj.name;
                    }
                });
            },
            clickKeyboard() {
                this.isFocus = !this.isFocus;
                if (this.isFocus === true) {
                    document.getElementById('textfocus').focus();
                } else {
                    document.getElementById('textfocus').blur();
                }
            },
            clickTextHandle() {
                this.isFocus = true;
            },
            focusIpt() {
                this.isFocus = false;
                this.isMultimediaFocus = true;
                document.getElementById('textfocus').focus();
                // document.body.scrollTop = document.body.scrollHeight
            },
            blurIpt() {
                this.isFocus = true;
                this.isMultimediaFocus = false;
                document.getElementById('textfocus').blur();
            }
        },
    }
</script>

<style lang="scss">
    .repair-fault-des-layout {

        .fault-des-content-part {
            padding-top: 0.4rem;
            padding-left: 0.4rem;
            font-size: 1.2em;
            text-align: left;
        }

        .fault-des-img-part {
            padding-left: 0.4rem;
        }
    }
</style>